package cc.iotkit.test;

import cc.iotkit.plugins.mattress.parser.CRC8;
import cc.iotkit.plugins.mattress.parser.MsgPack;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.msgpack.jackson.dataformat.MessagePackFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SenderV22 {

	private static String[] device_ids = {"759","31013","31218","31219"};

	public static void main(String[] args) {
		SenderV22 o = new SenderV22();
		try {
			for (int i=0; i<10; i++){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			o.sendMsg(i);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void sendMsg(int i) throws IOException{
		ObjectMapper objectMapper = new ObjectMapper(
				new MessagePackFactory());
        MsgPack msg = new MsgPack();
        Map<String, Object> d=new HashMap<String, Object>();
        //case1:mov
        //d.put("st", "mov");
        //case2:on
        //d.put("st", "on");
        //case3:call
        d.put("st", "call");
        //List<Integer> p = Arrays.asList(8,9);//Arrays.asList(1,2);
        List<Integer> p = new ArrayList<Integer>();
        p.add(8-(int)(Math.random() * 9));
        p.add(9-(int)(Math.random() * 10));
        d.put("p", p);
        
        d.put("hb", String.valueOf((int)(Math.random() * 101)-(i%2)));
        d.put("br", String.valueOf((int)(Math.random() * 50)));
		d.put("wt", String.valueOf((int)(Math.random() * 1)));
		msg.setD(d);
		Integer index = (int)(Math.random() * 3);
//		msg.setSn(device_ids[index]);
		msg.setSn("Z50709");
		msg.setV(2);
		System.out.println("***************"+msg.toString());

        byte[] bytes = objectMapper.writeValueAsBytes(msg);
        
        Socket socket=new Socket("127.0.0.1",9868);
        OutputStream os = socket.getOutputStream();
        byte crc = CRC8.calcCrc8(bytes);
        byte[] header = {(byte)0xab, (byte)0xcd, (byte)bytes.length, crc};
        os.write(header);
        os.write(bytes);
        os.close();
        socket.close();
        
	}
}
